<template>
  <el-dialog
    v-model="dialogVisible"
    :title="rowId ? '编辑' : '配置'"
    width="500"
    :before-close="handleClose"
  >
    <el-form
      ref="apiFormRef"
      style="max-width: 600px"
      :model="dataForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="平台名称" prop="remark">
        <el-input v-model="dataForm.remark" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="Api分组" prop="groupId">
        <infinite-scroll-select
          v-model="dataForm.groupIndex"
          :options="groupList"
          optionLabel="name"
          optionKey="id"
          :optionValue="(e) => groupList.indexOf(e)"
          :loading="selectLoading"
          :has-more="hasMore"
          placeholder="请选择"
          clearable
          filterable
          @load-more="loadMore"
          @change="handleChangeSelect"
        />
      </el-form-item>
      <el-form-item label="App" prop="app">
        <el-input v-model="dataForm.app" placeholder="" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="号码或邮箱" prop="method">
        <el-input
          :value="dataForm.method === 'mobile' ? '号码' : dataForm.method === 'email' ? '邮箱' : ''"
          placeholder=""
          :disabled="true"
        ></el-input>
      </el-form-item>
      <el-form-item label="国家" prop="country" label-position="right">
        <el-select v-model="dataForm.country" placeholder="请选择" :clearable="true" filterable>
          <el-option
            v-for="item in countriesList"
            :key="item.countryCode"
            :label="item.countryName"
            :value="item.countryCode"
          >
            <span class="flag-icon" :class="`flag-icon-${item.countryCode.toLowerCase()}`"></span>
            <span style="margin-left: 5px">{{ item.countryName }}</span>
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button v-loading="loading" type="primary" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import InfiniteScrollSelect from "@/components/InfiniteScrollSelect/index.vue";
import { throttle } from "@/utils/index";
import { addConfig, editConfig } from "@/api/platformConfig/index.api";
import { getData } from "@/api/equipmentManagement/numberManage/grouping.api";
import useToggle from "@/hooks/useToggle";
const [dialogVisible, , setDialogVisible] = useToggle();
const [loading, , setLoading] = useToggle();
const [selectLoading, , setSelectLoading] = useToggle();
const dataForm = ref({
  groupIndex: "",
  groupId: "",
  method: "",
  country: "",
  remark: "",
});
const rules = ref({
  remark: [{ required: true, message: "请输入平台名称", trigger: "blur" }],
  groupId: [{ required: true, message: "请选择api分组", trigger: "blur" }],
});
const emit = defineEmits(["refresh"]);

const rowId = ref();
const isEdist = ref(false);
const configId = ref("");
const handleOpen = (rows, id, formRow, formId) => {
  if (formRow) {
    isEdist.value = true;
    dataForm.value.groupIndex = groupList.value.map((item) => item.id).indexOf(formRow.groupId);
    dataForm.value.groupId = formRow.groupId;
    dataForm.value.method = formRow.method;
    dataForm.value.app = formRow.app;
    dataForm.value.remark = formRow.remark;
    dataForm.value.country = formRow.country;
    countriesList.value = [];
    const row = groupList.value.find((item) => item.id === dataForm.value.groupId);
    if (row) countriesList.value = row.countries;
  } else {
    isEdist.value = false;
    dataForm.value.groupIndex = void undefined;
    dataForm.value.groupId = void undefined;
    dataForm.value.method = void undefined;
    dataForm.value.app = void undefined;
    dataForm.value.country = void undefined;
    countriesList.value = void undefined;
  }

  rowId.value = formId || void undefined;

  nextTick(() => {
    configId.value = id;
    setDialogVisible(true);
  });
};

const handleClose = () => {
  setDialogVisible(false);
};

const countriesList = ref([]);

const handleChangeSelect = (val) => {
  dataForm.value.country = void undefined;
  const row = groupList.value[val];
  dataForm.value.groupId = row.id;
  dataForm.value.method = row.method;
  dataForm.value.app = row.app;
  countriesList.value = row.countries;
};

const paging = ref({
  page: 1,
  size: 50,
});
const groupCount = ref(0);
const groupList = ref([]);
const hasMore = ref(true);
const getGroupList = async () => {
  setSelectLoading(true);
  const res = await getData(paging.value).finally(() => setSelectLoading(false));
  groupList.value = !groupList.value.length ? res.rows : [...groupList.value, ...res.rows];
  groupCount.value = res.count;

  if (res.count <= groupList.value.length) {
    hasMore.value = false;
  }
};

const loadData = throttle(() => {
  paging.page++;
  getGroupList();
}, 500);

const loadMore = () => {
  if (groupList.value.length < groupList.value) {
    loadData();
  }
};

const apiFormRef = ref(null);
const submit = async () => {
  if (!apiFormRef.value) return;

  await apiFormRef.value.validate((valid, fields) => {
    if (valid) {
      setLoading(true);
      const params = JSON.parse(JSON.stringify(dataForm.value));

      const config = [
        {
          key: "country",
          value: params.country || "",
        },
        {
          key: "method",
          value: params.method,
        },
        {
          key: "app",
          value: params.app,
        },
        {
          key: "groupId",
          value: params.groupId,
        },
      ];
      if (rowId.value)
        return editConfig({
          instanceId: configId.value,
          thirdId: rowId.value,
          remark: dataForm.value.remark,
          config,
        })
          .then(() => {
            dialogVisible.value = false;
            setLoading(false);
            emit("refresh");
            ElMessage({
              message: "配置成功",
              type: "success",
            });
          })
          .finally(() => {
            setLoading(false);
            dialogVisible.value = false;
          });
      addConfig({
        thirdId: configId.value,
        remark: dataForm.value.remark,
        config,
      })
        .then(() => {
          dialogVisible.value = false;
          setLoading(false);
          emit("refresh");
          ElMessage({
            message: "配置成功",
            type: "success",
          });
        })
        .finally(() => {
          setLoading(false);
          dialogVisible.value = false;
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};

onMounted(() => {
  getGroupList();
});

defineExpose({
  handleOpen,
});
</script>
<style scoped>
/* 可以自定义下拉框样式 */
:deep(.el-select-dropdown__wrap) {
  max-height: 300px;
}
</style>
